package com.limetalks.util;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.limetalks.dao.StreamDAO;
import com.limetalks.dao.UserDAO;
import com.limetalks.data.Stream;
import com.limetalks.data.User;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		EntityManagerFactory emf = Persistence.createEntityManagerFactory("LimeTalksUnit");
		EntityManager em = emf.createEntityManager();
//		Query streamInsertQuery = em.createNativeQuery("INSERT INTO stream(name) VALUES(:name)");
//		Query userInsertQuery = em.createNativeQuery("INSERT INTO user(name, email, password) VALUES(:name, :email, :password)");

		
//		Query lastIdQuery = emf.createEntityManager().createNativeQuery("SELECT LAST_INSERT_ID()");		
		
		StreamDAO streamDAO = new StreamDAO(emf);
		UserDAO userDAO = new UserDAO(emf);
		User user;
		Stream stream;
		Date d1;
		Date d2;
		Date d3;
		try{
			for(int i = 1; i <= 2; i++){
				d1 = new Date();
	//			user = userDAO.findById(i);
				user = new User();
				user.setEmail("mail" + i);
				user.setName("name" + i);
				user.setPassword("password" + i);	
				
				/*em.getTransaction().begin();
				
				userInsertQuery.setParameter("name", user.getName());
				userInsertQuery.setParameter("email", user.getEmail());
				userInsertQuery.setParameter("password", user.getPassword());
				
				userInsertQuery.executeUpdate();
				user.setId(((Integer) lastIdQuery.getSingleResult()));*/
				userDAO.save(user);
				
				
				d2 = new Date();
				System.err.println("User saved (" + (d2.getTime() - d1.getTime()) + " ms) - " + user);
				
				stream = new Stream();
				stream.setName("stream" + i);
				stream.setMaster(user);
				
				/*streamInsertQuery.setParameter("name", stream.getName());
				streamInsertQuery.executeUpdate();
				stream.setId(((Integer) lastIdQuery.getSingleResult()));*/
				streamDAO.save(stream);
				
				d3 = new Date();
				System.err.println("Stream saved (" + (d3.getTime() - d2.getTime()) + " ms) - " + stream);
				
//				em.getTransaction().commit();
				
				/*System.err.println(d2.getTime() - d1.getTime() + " - " + user);
				stream = streamDAO.findById(i);
				d3 = new Date();
				System.err.println(d3.getTime() - d2.getTime() + " - " + stream);*/
			}
		}finally{
			em.close();
			System.err.println("!!!!!! END");
		}
	}

}
